<template>
  <div>
    <el-tabs type="card" v-model="editableTabsValue" @tab-click="handleClick" @tab-remove="removeResource">
      <el-tab-pane
        v-for="(item) in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
        closable>
        <div class="videoExample" v-if="item.title === '视频'">
          <p>{{item.content}}</p>
          <video controls="controls" preload="auto" id="lecture" :src="item.url">
            当前浏览器不支持video直接播放，推荐使用Chrome浏览器进行播放
          </video>
        </div>
        <div v-if="item.title === '作业'">
          <tasks :taskData="{ldq:'ldq'}" @reldq="reldq" />
        </div>
      </el-tab-pane>
      <el-tab-pane label="作业" name="task" >
        <span slot="label">
          作业
          <!-- <i class="el-icon-circle-check" 
            :style="{'color':0?'#409eff':'grey'}"
          /> -->
        </span>
        <tasks :taskData="{ldq:'ldq'}" @reldq="reldq" />
      </el-tab-pane>
      <!-- 
      <el-tab-pane label="学习任务" name="task" v-if="chapterData.task.title">
        <span slot="label">
          学习任务
          <i class="el-icon-circle-check" 
            :style="{'color':0?'#409eff':'grey'}"
          />
        </span>
        <tasks :taskData="{ldq:'ldq'}" @reldq="reldq" />
      </el-tab-pane>
      <el-tab-pane label="PPT" name="ppt" v-if="chapterData.ppt.title">
        <span slot="label">
          PPT
          
          此处判断学生是否完成是视频学习任务，
          完成颜色为'#409eff' 未完成为'grey'
         
          <i class="el-icon-circle-check" 
            :style="{'color':0?'#409eff':'grey'}"
          />
        </span>
        <PPT/>
        PPT
      </el-tab-pane>
      <el-tab-pane label="直播" name="stream" v-if="chapterData.stream.title">
        <span slot="label">
          直播
          <i class="el-icon-circle-check" 
            :style="{'color':0?'#409eff':'grey'}"
          />
        </span>
        直播
        <Video2/>
      </el-tab-pane> -->
      <el-tab-pane name="add">
        <span slot="label">
          <el-dropdown placement="bottom" trigger="click" @command="addResource" @visible-change="showTabContent">
            <span class="el-dropdown-link" style="padding: 8px;font-size:20px;font-weight:bold;">
              +
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item key="video" command="video">添加视频</el-dropdown-item>
              <el-dropdown-item key="ppt" command="ppt">添加ppt</el-dropdown-item>
              <el-dropdown-item key="task" command="task">添加作业</el-dropdown-item>
              <el-dropdown-item key="stream" command="stream">添加直播</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="选择资源"
      :visible.sync="dialogVisible"
      width="40%"
      @close="closeDialog">
      <div class="resourceDialog">
          <label>选择资源：</label>
          <el-autocomplete
            class="inline-input"
            v-model="state"
            :fetch-suggestions="querySearch"
            placeholder="请选择资源"
            @select="handleSelect"
            value-key=title
            :popper-append-to-body="false"
            clearable
          ></el-autocomplete>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="saveResource()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '../../../api.js'
import tasks from './task/tasks.vue'
import Video from './creation/Video.vue'
import Video2 from './creation/Video2.vue'
import PPT from './creation/PPT.vue'
export default {
  name: 'Creation',
  components: { tasks, Video, PPT, Video2 },
  props: ['chapterData'],
  data () {
    return {
      editableTabs: [], // 加载对应节的资源
      editableTabsValue: 'task', // 默认显示tab的名称
      reldq: '',
      selectedResource: '',
      dialogVisible: false,
      resourceType: [{value: 'video', label: '视频'}],
      resourceTypeValue: '',
      filteredResource: [],
      state: '',
      courseResource: [],
      baseUrl: ''
    }
  },
  async mounted () {
    // 获取该课程的所有资源
    await api['getCourseResourceInfo'](this.$route.params.courseId).then(res => {
      this.courseResource = res.data.data.results
    })
    // baseurl
    const env = await process.env
    this.baseUrl = env.baseUrl + '/api/course/section?path='
    // 把当前节的课程资源加载到tab上
    if (this.chapterData.resources.length) {
      this.isSectionResourceExist = true
      this.chapterData.resources.forEach(res => {
      // 判断资源类型，添加对应类型的资源
        if (res.general === 'video') {
          this.editableTabs.push({
            title: '视频',
            name: res.id.toString(),
            content: res.title,
            url: this.baseUrl + res.url})
        }
      })
      this.editableTabsValue = this.editableTabs[0].name // 默认当前显示tab的名字
      this.editableTabsValue = 'task' // 默认当前显示tab的名字
    }
  },
  methods: {
    // 点击tab的操作
    handleClick (tab, event) {
      if (tab.name === 'addResource') {
        this.addResource()
      } else if (tab.name === 'remove') {
        this.removeResource()
      } else {
        this.editableTabsValue = tab.name
      }
    },
    // 点击加号，根据选择的下拉资源类型，筛选可用资源
    addResource (dropdownItem) {
      // 筛选视频类型可用资源
      switch (dropdownItem) {
        case 'video': {
          this.filterResource('video')
          break
        }
        case 'ppt': {
          this.filterResource('ppt')
          break
        }
      }
      this.state = ''
    },
    showTabContent (e) {
      if (!e && this.editableTabs[0]) {
        this.editableTabsValue = this.editableTabs[0].name // 默认当前显示tab的名字
      }
    },
    removeResource (targetName) {
      this.$confirm('是否确定删除当前选中课程资源?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 页面删除tab
        let tabs = this.editableTabs
        let activeName = this.editableTabsValue
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        this.editableTabsValue = activeName
        this.editableTabs = tabs.filter(tab => tab.name !== targetName)
        // 删除资源
        api.delSectionResource(this.chapterData.id, parseInt(targetName)).then(res => {
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
      })
    },
    // 关闭选择视频资源对话框
    closeDialog () {
      this.dialogVisible = false
      this.selectedResource = {}
      this.filteredResource = []
    },
    saveResource () {
      // 发送数据到后端
      let passData = {
        section: this.chapterData.id,
        resource: this.selectedResource.id
      }
      if (this.editableTabs.filter(tab => tab.name === this.selectedResource.id.toString()).length) {
        this.filteredResource = []
        this.dialogVisible = false
        return this.$alert('选中的视频已经添加了', '注意', {
          confirmButtonText: '确定'
        })
      }
      api['matchSectionAndResource'](passData).then(res => {
        // 添加一个新的视频tab
        if (this.selectedResource.general === 'video') {
          return this.editableTabs.push({
            title: '视频',
            name: this.selectedResource.id.toString(),
            content: this.selectedResource.title,
            url: this.baseUrl + this.selectedResource.url
          })
        }
      }).then(_ => {
        this.dialogVisible = false
        this.editableTabsValue = this.editableTabs[this.editableTabs.length - 1].name
        // 重置筛选资源
        this.filteredResource = []
      }).catch(err => {
        console.log(err)
      })
    },
    // 保存选中的资源
    handleSelect (item) {
      this.selectedResource = item
    },

    // 判断当前课程是否存在资源，不存在则弹出warning
    filterResource (resourceType) {
      api['getCourseResourceInfo'](this.$route.params.courseId, '', resourceType).then(res => {
        this.filteredResource = res.data.data.results
        if (this.filteredResource.length === 0) {
          this.$message({
            message: '当前课程没有相应资源，请先在资源管理页面添加！',
            type: 'warning'
          })
        } else {
          this.dialogVisible = true
        }
      })
    },

    // 自定义input搜索筛选框
    querySearch (queryString, cb) {
      var results = queryString ? this.filteredResource.filter(this.createFilter(queryString)) : this.filteredResource
      // 调用 callback 返回建议列表的数据
      cb(results)
    },

    createFilter (queryString) {
      return (resourceTitle) => {
        return (resourceTitle.title.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    }
  }
}
</script>

<style>
  .videoExample video{
    width: 85%;
    border: 1px solid lightgrey;
  }
</style>